package com.hafu.dao;

import com.hafu.model.KuCun;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class KuCunDao {
    public static ArrayList<KuCun> list=new ArrayList<>();
    public static ArrayList<KuCun> getKuCunList() {
        Connection conn = DbUtil.getConn();
        String sql = "select * from kucun";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                String id = resultSet.getString("id");
                String spname = resultSet.getString("spname");
                int num = resultSet.getInt("num");
                KuCun kuCun1 = new KuCun(id, spname, num);
                list.add(kuCun1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
    public KuCun getKuCunBySpName(String spName,Connection conn) throws SQLException{
        String sql = "select * from kucun where spname=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, spName);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            String id = resultSet.getString("id");
            String name = resultSet.getString("spname");
            int num = resultSet.getInt("num");
            KuCun kucun=new KuCun(id,name,num);
            return kucun;
        }
        return null;
    }

    public boolean addKuCun(KuCun kucun,Connection conn) {
        String sql = "insert into kucun(spname,num) values(?,?)";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            System.out.println(kucun.getSpname());
            System.out.println(kucun.getNum());
            preparedStatement.setString(1, kucun.getSpname());
            preparedStatement.setInt(2, kucun.getNum());
            int i = preparedStatement.executeUpdate();
            if(i>0){
                return true;
            }else return false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Boolean updateKuCun(KuCun kuCunByName, Connection conn) {
        String sql = "update kucun set num=? where spname=?";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setInt(1, kuCunByName.getNum());
            preparedStatement.setString(2, kuCunByName.getSpname());
            int i = preparedStatement.executeUpdate();
            if(i>0){
                return true;
            }else return false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}